package com.runrunfast.face.service;

import com.alibaba.fastjson.JSONObject;
import com.runrunfast.face.constant.YoutuUrl;
import com.runrunfast.face.dao.PersonRelationRepository;
import com.runrunfast.face.entity.PersonRelation;
import com.runrunfast.face.service.common.ColourService;
import com.runrunfast.face.service.common.YoutuService;
import com.runrunfast.face.util.ToolUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 人脸库Service
 *
 * @author YangNing
 */
@Service
@Transactional
public class PersonService {

    private static Logger logger = LoggerFactory.getLogger(PersonService.class);
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    PersonRelationRepository personRelationRepository;
    @Autowired
    ColourService colourService;
    @Autowired
    YoutuService youtuService;

    /**
     * 获取Person
     *
     * @param accountUuid 彩之云account_uuid
     * @return
     */
    public PersonRelation getPersonByAccountUuid(String accountUuid) {
        return personRelationRepository.findByAccountUUid(accountUuid);
    }

    /**
     * 获取Person
     *
     * @param personId 优图person_id
     * @return
     */
    public PersonRelation getPersonByPersonId(String personId) {
        return personRelationRepository.findByPersonId(personId);
    }

    /**
     * 添加person到优图
     *
     * @param uuid
     * @param name
     * @param faceGroupId
     * @return
     */
    public PersonRelation addPerson(String uuid, String name, Integer faceGroupId) {
        // TODO: 2018/5/20 新建person时的name不能重复
        PersonRelation personRelation = new PersonRelation();
        JSONObject params = new JSONObject();
        params.put("name", ToolUtil.isEmpty(name) ? "" + System.currentTimeMillis() : name);
        params.put("face_group_id", faceGroupId);
        params.put("info", "{}");
        HttpEntity requestEntity = youtuService.initEntity(params, YoutuUrl.PERSONS, HttpMethod.POST);
        ResponseEntity<JSONObject> response = restTemplate.exchange(YoutuUrl.HOST + YoutuUrl.PERSONS, HttpMethod.POST, requestEntity, JSONObject.class);
        logger.info(response.getBody().toJSONString());
        personRelation.setAccountUUid(uuid);
        personRelation.setPersonId("" + response.getBody().getJSONObject("data").getInteger("person_id"));
        personRelationRepository.save(personRelation);
        return personRelation;
    }

    /**
     * 根据手机号上传人脸图片到优图
     *
     * @param phone       彩之云用户手机号
     * @param faceGroupId 人脸库id
     * @param file        人脸图片
     * @return
     */
    public JSONObject addPersonFaceToFaceGroup(String phone, Integer faceGroupId, MultipartFile file) {
        JSONObject accountInfo = colourService.getAccountByPhone(phone);
        PersonRelation personRelation = getPersonByAccountUuid(accountInfo.getString("uuid"));
        if (null == personRelation) {
            personRelation = addPerson(accountInfo.getString("uuid"), accountInfo.getString("name"), faceGroupId);
        }
        String apiPath = YoutuUrl.PERSON_FACES.replace("{person-id}", personRelation.getPersonId());
        String tempFileName = UUID.randomUUID() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String tempFilePath = ToolUtil.getTempPath() + tempFileName;
        File tempFile = new File(tempFilePath);
        try {
            file.transferTo(tempFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileSystemResource fileSystemResource = new FileSystemResource(tempFilePath);
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        form.add("face_image", fileSystemResource);
        HttpEntity requestEntity = youtuService.initFileEntity(form, apiPath, HttpMethod.POST);
        ResponseEntity<JSONObject> response = restTemplate.exchange(YoutuUrl.HOST + apiPath, HttpMethod.POST, requestEntity, JSONObject.class);
        return response.getBody();
    }

}
